package cn.openea.perpartner.cms.factory;

import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.cms.web.entity.SysRole;
import cn.openea.perpartner.cms.web.service.ISysRoleService;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.common.core.utils.spring.SpringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-07-21 14:33
 */
public class UserContext {
    private static final ThreadLocal<ThreadContext> context = new ThreadLocal<>();

    public static ThreadContext getContext() {
        // 初始化线程对像
        ThreadContext threadContext = context.get();
        if (threadContext == null) {
            threadContext = new ThreadContext();
            context.set(threadContext);
        }
        return threadContext;
    }

    public static void setLoginUser(LoginBody loginBody) {
        getContext().setLoginUser(loginBody);
    }

    public static void clear() {
        context.remove();
    }

    public static LoginBody getLoginUser() {
        return getContext().getLoginUser();
    }

    public static String getUserId() {
        LoginBody loginBody = getContext().getLoginUser();
        return loginBody == null ? null : loginBody.getUserid();
    }

    public static String getUserName() {
        LoginBody loginBody = getContext().getLoginUser();
        return loginBody == null ? null : loginBody.getUsername();
    }

    public static String getUserRole() {
        String userRole = getContext().getUserRole();
        if (StrUtil.isBlank(userRole)) {
            ISysRoleService roleService = SpringUtils.getBean(ISysRoleService.class);
            List<SysRole> roles = roleService.selectRolesByUserId(getUserId());
            List<String> list = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            userRole = !roles.isEmpty() ? StringUtils.join((list), ",") : "common";
            getContext().setUserRole(userRole);
        }
        return userRole;
    }
}
